#!/usr/bin/perl

##HACKABOT_HELP##
# Print scores from something++ and something-- statements
# !score [something | --low | --high | --nicks]
##HACKABOT_HELP##

use strict;
use DBI;
use Time::localtime;
use XML::Simple;

my $CONFIG = XMLin($ENV{'HACKABOT_CFG'});
my $DBCFG = $CONFIG->{'cmdconfig'}->{'database'};

my $dbhost = $DBCFG->{'host'};
my $dbname = $DBCFG->{'name'};
my $dbuser = $DBCFG->{'user'};
my $dbpass = $DBCFG->{'pass'};

sub get_score {
	my $name = shift;
	my ($dbh, $sth);

	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 0 });
	if (!$dbh) {
		die "score: Failed to connect to database\n";
	}
	
	$name = $dbh->quote($name);
	
	$sth = $dbh->prepare("SELECT value FROM score WHERE name = $name");
	$sth->execute;
	my $row = $sth->fetchrow_hashref;
	my $value = $row->{'value'};
	$sth->finish();

	$dbh->disconnect;

	return $value;
}

sub get_list {
	my $order = shift;
	my $chan = shift;
	my ($dbh, $sth);
	
	$dbh = DBI->connect("DBI:mysql:$dbname:$dbhost", $dbuser, $dbpass, { PrintError => 1 });
	if (!$dbh) {
		die "score: Failed to connect to database\n";
	}

	if ($order eq "low") {
		$order = "ASC";
	}
	elsif ($order eq "high") {
		$order = "DESC";
	}
	else {
		die "Unknown order $order\n";
	}

	my $where = "";
	if (defined $chan) {
		my $names = `echo 'names $chan' | $ENV{'HACKABOT_DIR'}/scripts/client`;
		chomp $names;
		$names =~ s/^\S+\s+\S+\s+//;
		$where = "WHERE 0";
		foreach $_ (split(/\s+/, $names)) {
			$_ = $dbh->quote($_);
			$where .= " OR name = $_";
		}
	}	

	$sth = $dbh->prepare("SELECT name, value FROM score $where ORDER BY value $order LIMIT 3");
	$sth->execute;
	my @list;
	for (my $i = 0; $i < 3; $i++) {
		$list[$i] = $sth->fetchrow_hashref;
	}
	$sth->finish();

	$dbh->disconnect;

	return @list;
}


my ($name, $chan);
while (<>) {
	if (/^msg\s+(\S+.*)/) {
		$name = $1;
	}
	elsif (/^to\s+(#\S+)/) {
		$chan = $1;
	}
}

if (defined $name and not $name =~ /(-h|--high|-l|--low|-n|--nicks)/) {
	$name =~ s/^(\S+)/$1/;
	my $val = get_score($name);
	if ($val == "") { $val = 0; }
	if ($val == "1") {
		print "send $name has scored $val point!\n";
	}
	else {
		print "send $name has scored $val points!\n";
	}
}
elsif (defined $name and $name =~ /(-h|--high|-l|--low|-n|--nicks)/) {
	my $order;
	my $nicks;
	
	$order = ($name =~ /(-l|--low)/)? "low" : "high";
	$nicks = ($name =~ /(-n|--nicks)/)? $chan : undef;
	
	my @list = get_list($order, $nicks);
	print "sendnext\n";
	
	if ($order eq "high") {
		print "Top 3:\n";
	}
	else {
		print "Losers:\n";
	}
	
	for (my $i = 0; $i < 3; $i++) {
		print "  $list[$i]->{'value'} $list[$i]->{'name'}\n";
	}
}
else {
	my @list = get_list("high");
	print "sendnext\n";
	print "Top 3:\n";
	for (my $i = 0; $i < 3; $i++) {
		print "  $list[$i]->{'value'} $list[$i]->{'name'}\n";
	}
}
